package cn.itcast.p2p20.fragments;


import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.itcast.p2p20.R;
import cn.itcast.p2p20.act.MyApplication;
import cn.itcast.p2p20.bean.RegisterData;
import cn.itcast.p2p20.bean.request.RegisterRequest;
import cn.itcast.p2p20.bean.response.RegisterResponse;
import cn.itcast.p2p20.net.BaseRequest;
import cn.itcast.p2p20.net.SuccessResultCallback;
import cn.itcast.p2p20.utils.Util;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterFragment extends BaseFragment implements SuccessResultCallback<RegisterResponse> {


    @InjectView(R.id.fragment_login_username)
    EditText fragmentLoginUsername;
    @InjectView(R.id.fragment_login_password)
    EditText fragmentLoginPassword;
    @InjectView(R.id.fragment_register)
    Button fragmentRegister;

    @Override
    protected void initData() {

        showSuccessStateLayout();
    }

    @Override
    protected void initView(View childFragmentView) {

        ButterKnife.inject(this, childFragmentView);
    }

    @Override
    protected String getTitle() {
        return null;
    }

    @Override
    protected int getContentLayoutRes() {
        return R.layout.fragment_register;
    }


    @OnClick(R.id.fragment_register)
    public void onClick() {

        String username = fragmentLoginUsername.getText().toString().trim();
        String password = fragmentLoginPassword.getText().toString().trim();
        if (checkUsername(username) && checkPassword(password)) {

            sendRequest(new RegisterRequest(username, password), RegisterResponse.class, this);
        }
    }


    private boolean checkPassword(String password) {

        if (TextUtils.isEmpty(password)) {

            Util.showToast(mContext, "密码不能为空");
            return false;
        }

        if (password.length() < 6) {

            Util.showToast(mContext, "密码不能少于6位");
            return false;
        }

        return true;
    }

    private boolean checkUsername(String username) {

        if (TextUtils.isEmpty(username)) {

            Util.showToast(mContext, "用户名不能为空");
            return false;
        }

        if (username.length() < 6) {

            Util.showToast(mContext, "用户名不能少于6位");
            return false;
        }

        return true;
    }

    @Override
    public void onSuccessResult(BaseRequest request, RegisterResponse response) {

        RegisterData registerData = response.data;
        if (registerData != null && registerData.getUser() != null) {


            ((MyApplication) mContext.getApplicationContext()).getBus().post(registerData.getUser());
            getActivity().finish();
        }

    }
}
